import pandas as pd
import numpy as np
from datetime import datetime, timedelta

def generate_transaction_data(num_records=10000):
    np.random.seed(42)
    
    # 生成交易ID
    transaction_ids = [f"TXN{100000 + i}" for i in range(num_records)]
    
    # 生成客户ID
    customer_ids = [f"CUST{1000 + np.random.randint(0, 1000)}" for _ in range(num_records)]
    
    # 生成产品类别
    product_categories = ["电子产品", "服装", "食品", "家居", "美妆", "书籍", "玩具"]
    categories = np.random.choice(product_categories, size=num_records, p=[0.2, 0.25, 0.15, 0.1, 0.15, 0.05, 0.1])
    
    # 生成交易金额
    amounts = np.random.lognormal(mean=7, sigma=0.7, size=num_records)
    amounts = np.clip(amounts, 10, 5000)
    
    # 生成交易日期 (近3个月)
    start_date = datetime.now() - timedelta(days=90)
    dates = [start_date + timedelta(days=np.random.randint(0, 90)) for _ in range(num_records)]
    
    # 生成是否退款标志 (10%的交易退款)
    is_refund = np.random.binomial(1, 0.1, num_records)
    
    # 生成退款理由 (仅针对退款交易)
    refund_reasons = ["质量问题", "尺寸不合适", "产品描述不符", "发货延迟", "不想要了", "商品损坏", "其他"]
    refund_reason_list = []
    for refund in is_refund:
        if refund:
            reason = np.random.choice(refund_reasons, p=[0.3, 0.15, 0.15, 0.1, 0.2, 0.05, 0.05])
            refund_reason_list.append(reason)
        else:
            refund_reason_list.append(None)
    
    # 创建DataFrame
    df = pd.DataFrame({
        "transaction_id": transaction_ids,
        "customer_id": customer_ids,
        "product_category": categories,
        "transaction_amount": amounts,
        "transaction_date": dates,
        "is_refund": is_refund,
        "refund_reason": refund_reason_list
    })
    
    # 为退款交易添加退款日期 (交易日期后1-15天)
    refund_dates = []
    for idx, row in df.iterrows():
        if row["is_refund"]:
            days_later = np.random.randint(1, 16)
            refund_dates.append(row["transaction_date"] + timedelta(days=days_later))
        else:
            refund_dates.append(None)
    
    df["refund_date"] = refund_dates
    
    return df

# 生成数据并保存为CSV
if __name__ == "__main__":
    transaction_data = generate_transaction_data(10000)
    transaction_data.to_csv("transaction_data.csv", index=False)
    print("数据生成完成，已保存至 transaction_data.csv")    